package com.his.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.his.entity.dto.Register;
import com.his.mapper.RegisterMapper;
import com.his.service.IClinicService;
import com.his.entity.vo.RegisterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class ClinicServiceImpl implements IClinicService {
    @Autowired
    private RegisterMapper registerMapper;

    /**
     * 统计今日已就诊人数
     *
     * @return
     */
    @Override
    public int seen() {
        return getTodayCount(DateUtil.date(), 1);
    }

    /**
     * 统计今日排队人数
     *
     * @return
     */
    @Override
    public int queue() {
        return getTodayCount(DateUtil.date(), 0);
    }

    private int getTodayCount(Date tDate, int status) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(tDate);
        return registerMapper.selectList(Wrappers.lambdaQuery(Register.class)
                        .le(Register::getVisitDate, date)
                        .ge(Register::getVisitDate, date)
                        .eq(Register::getVisitState, status))
                .size();
    }

    /**
     * 获取今日预约患者信息
     *
     * @return
     */
    @Override
    public List<RegisterVO> selectClinicRegistList(Register register) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(DateUtil.date());
        List<Register> list = registerMapper.selectList(Wrappers.lambdaQuery(Register.class)
                .eq(Register::getVisitState, 0)
                .le(Register::getVisitDate, date)
                .ge(Register::getVisitDate, date)
                .like(register.getRealName() != null, Register::getRealName, register.getRealName())
                .orderBy(true, true, Register::getCreateTime));

        final int[] count = {1};
        List<RegisterVO> registerVOS = BeanUtil.copyToList(list, RegisterVO.class);
        registerVOS.forEach(registerVO -> {
            registerVO.setPatientId(count[0]++);
        });

        return registerVOS;
    }

    /**
     * 跳过患者
     *
     * @param registerId
     */
    @Override
    public void skipPatient(String registerId) {
        Register register = registerMapper.selectById(registerId);
        if (Objects.isNull(register)) {
            throw new RuntimeException("不存在此患者！");
        }

        Date lastCreateTime = registerMapper.getLastCreateTime();
        Calendar cal = Calendar.getInstance();
        cal.setTime(lastCreateTime);
        cal.add(Calendar.SECOND, 1);
        register.setCreateTime(cal.getTime());

        registerMapper.updateById(register);

    }
}
